import { createRouter, createWebHistory } from 'vue-router'
import { cloneDeep } from 'lodash-es'

import { useStore } from '/@/store'
import routes, { indexRoute, menuOptions } from './modules/routes'
import sysRoutes from './modules/sysRoutes'
import catchRoutes from './modules/catchRoutes'

export const loadingBarApiRef = {}
export { indexRoute, menuOptions, routes }

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_PUBLIC_PATH),
  routes: [
    {
      path: '/',
      component: () => import('/@/layouts/Default.vue'),
      children: [
        { path: '', redirect: indexRoute?.path || '/404' },
        ...routes,
      ]
    },
    ...sysRoutes,
    ...catchRoutes
  ],
  scrollBehavior: () => ({ left: 0, top: 0 })
})

router.beforeEach((to, from, next) => {
  if (!from || to.path !== from.path) {
    if (loadingBarApiRef.value) {
      loadingBarApiRef.value.start()
    }
  }
  next()
})

router.afterEach((to, from) => {
  if (!from || to.path !== from.path) {
    if (loadingBarApiRef.value) {
      loadingBarApiRef.value.finish()
    }
  }
})

export const defaultTitle = '行政调解管理系统'

router.beforeResolve((to, from, next) => {
  if (to.meta.title) {
    document.title = defaultTitle + ' - ' + to.meta.title
  } else {
    document.title = defaultTitle
  }

  next()
})

let defaultRoutes

export function setupRouter(app) {
  app.use(router)
  defaultRoutes = router.getRoutes()
}

export function setRoutes(ignoreRoutes = []) {
  const menus = cloneDeep(menuOptions)

  for (let rawRoute of defaultRoutes) {
    router.addRoute(rawRoute)

    if (ignoreRoutes.indexOf(rawRoute?.name) > -1) {
      const index = menus.findIndex(menu => menu.key === rawRoute.path)

      if (index > -1) {
        menus.splice(index, 1)
      }
    }
  }

  useStore().setMenus(menus)

  for (let name of ignoreRoutes) {
    if (router.hasRoute(name)) {
      router.removeRoute(name)
    }
  }
}

export default router
